import {PageParams} from '@/types/global.d'
import {partDb} from '@/api/lowdb.ts'
import {Part} from '@/types/part.d'
import {nanoid} from 'nanoid'
const fs = require('fs')

export const deleteParts = (ids: string[]) => {
    const parts: Required<Part>[] = partDb.read().value()
    for (let i = parts.length - 1; i >= 0; i--) {
        const part = parts[i]
        if (ids.includes(part.id)) {
            parts.splice(i, 1);
            // 删除关联的本地图片文件
            for (let image of part.images) {
                fs.unlinkSync(`part_images/${image}`)
            }
        }
    }
    partDb.write()
}

export const updatePart = (data: Part) => {
    const dbData: Part[] = partDb.read().value()
    const index = dbData.findIndex(part=>part.id === data.id)
    if (index !== -1) {
        dbData[index] = data
        partDb.write()
    }
}

export const getPart = (id: number) => {
    return partDb.read().find({ id }).value()
}

export const savePart = (data: Part) => {
    data.id = nanoid()
    partDb.read().push(data).write()
}

export const listParts = (pageParams: PageParams, part?: Partial<Part>) => {
    let parts: Required<Part>[] = partDb.read().value()
    parts.reverse()
    // 搜索匹配
    let nameCn = part?.nameCn
    if (nameCn) {
        parts = parts.filter(p => p.nameCn.includes(nameCn))
    }
    // 分页
    const startIndex = (pageParams.page - 1) * pageParams.pageSize
    const endIndex = startIndex + pageParams.pageSize
    return {
        records: parts.slice(startIndex, endIndex),
        total: parts.length,
    }
}
